package controller;
//SSM

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import pojo.Dept;
import service.DeptService;
import utils.Page;

import java.util.List;

@Controller                                    //Spring帮助实例化对象
@RequestMapping("/dept")                    // 相当于  @WebServlet(urlPatterns = "/user")
public class DeptController {
    //5个if判断(根据传的参数区分) 写成方法 方法加路径绑定 地址里面可以直接接

    @Autowired
    private DeptService deptService;

    @RequestMapping("/login")
    public String login(Dept dept){
        //登录逻辑 方法上写参数可以自动获取参数  name的值和user类中属性一致 参数自动映射过来

        boolean flag=deptService.login(dept);
        if(flag){
            return "index";
        }else{
            return "login";
        }
    }
    @RequestMapping("/list/{currentPage}")
    public String list(Dept dept, @PathVariable("currentPage") Integer currentPage, Model model){
        //查数据
        Page page=new Page();
        int totalCount = deptService.count(dept);
        page.setTotalCount(totalCount);
        page.setCurrentPage(currentPage);
        page.setTotalPage();

        //计算偏移量
        int offset= (currentPage-1)*page.getPageSize();
        List<Dept> depts = deptService.findAll(dept,offset,page.getPageSize());

        model.addAttribute("depts",depts);
        model.addAttribute("page",page);
        model.addAttribute("dept",dept);

        return "dept/list";
    }

    @RequestMapping("/toadd")
    public String toAdd(){
        //直接打开 转发
        return "dept/add";
    }
    @RequestMapping("/addSave")
    public String addSave(Dept dept){
        int result = deptService.addDept(dept.getDname());
        if(result>0){
            //类似重定向
            return "redirect:/dept/list/1";
        }else{
            return "error";
        }
    }
    @RequestMapping("/delete/{id}")
    public String deleteById(@PathVariable("id")Integer id){
        int result = deptService.deleteDeptById(id);
        if(result>0){
            return "redirect:/dept/list/1";
        }else{
            return "error";
        }
    }
    @RequestMapping("/toupdate/{id}")
    public String toupdate(@PathVariable("id")Integer id,Model model){
        Dept dept = deptService.findById(id);
        model.addAttribute("dept",dept);
        return "dept/update";
    }

    @RequestMapping("/updateSave")
    public String updateSave(Dept dept){
        int result=deptService.updateDept(dept);
        if(result>0){
            return "redirect:/dept/list/1";
        }else{
            return "error";
        }
    }

}
